package com.huiminpay.transaction.service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.AmountUtil;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.PaymentUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.merchant.api.MerchantService;
import com.huiminpay.paymentagent.api.PayChannelAgentService;
import com.huiminpay.paymentagent.api.conf.AliConfigParam;
import com.huiminpay.paymentagent.api.dto.AlipayBean;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.dto.PayChannelParamDTO;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.api.dto.QRCodeDto;
import com.huiminpay.transaction.api.service.PayChannelService;
import com.huiminpay.transaction.api.service.TransactionService;
import com.huiminpay.transaction.convert.PayChannelParamConvert;
import com.huiminpay.transaction.convert.PayOrderConvert;
import com.huiminpay.transaction.entity.PayChannelParam;
import com.huiminpay.transaction.entity.PayOrder;
import com.huiminpay.transaction.mapper.PayOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import java.time.LocalDateTime;
@Slf4j
@Service
public class TransactionServiceImpl implements TransactionService {
    @Value("${huiminpay.payurl}")
    private String payUrl;
    @Reference
    private MerchantService merchantService;
    @Reference
    private AppService appService;
    @Autowired
    private PayOrderMapper payOrderMapper;
    @Autowired
    private PayChannelService payChannelService;
    @Reference
    private PayChannelAgentService agentService;
//生成门店二维码
    @Override
    public String createStoreQRCode(QRCodeDto qrCodeDto) throws BusinessException {
        this.verifyAppAndStore(qrCodeDto.getMerchantId(), qrCodeDto.getAppId(), qrCodeDto.getStoreId());
        PayOrderDTO payOrderDTO = new PayOrderDTO();
        payOrderDTO.setMerchantId(qrCodeDto.getMerchantId());
        payOrderDTO.setAppId(qrCodeDto.getAppId());
        payOrderDTO.setStoreId(qrCodeDto.getStoreId());
        payOrderDTO.setChannel("huimin_c2b");
        payOrderDTO.setSubject(qrCodeDto.getSubject());
        payOrderDTO.setBody(qrCodeDto.getBody());
        String jsonString = JSON.toJSONString(payOrderDTO);
        log.info("transaction service createStoreQRCode,JsonString is {}",jsonString);
        String ticket = EncryptUtil.encodeUTF8StringBase64(jsonString);
        String payEntryUrl=payUrl+ticket;
        log.info("transaction service createStoreQRCode,pay‐entry is {}",payEntryUrl);
        return payEntryUrl;
    }
    @Override
    public PaymentResponseDTO<String> submitOrderByApli(PayOrderDTO payOrderDTO) throws BusinessException {
        //保存订单
        payOrderDTO.setPayChannel("ALIPAY_WAP");  //支付渠道
        PayOrderDTO orderDTO= this.save(payOrderDTO);
        //调代理服务对接支付宝
        return this.alipayH5(orderDTO);
    }

    @Override
    public void updatePayOrder(String tradeNo, String payChannelTradeNo, String tradeState) throws BusinessException {
        LambdaQueryWrapper<PayOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PayOrder::getTradeNo,tradeNo);
        PayOrder payOrder = new PayOrder();
        payOrder.setPayChannelTradeNo(payChannelTradeNo);
        payOrder.setTradeState(tradeState);
        payOrder.setUpdateTime(LocalDateTime.now());
        if ("2".equals(tradeState)){
        payOrder.setPaySuccessTime(LocalDateTime.now());

        }
        payOrderMapper.update(payOrder,wrapper);
        log.info("[交易服务更新订单]:{},{},{}",tradeNo,payChannelTradeNo,tradeState );
    }

    //保存订单
    private PayOrderDTO save(PayOrderDTO payOrderDTO){
        PayOrder payOrder = PayOrderConvert.INSTANCE.dto2entity(payOrderDTO);
        payOrder.setTradeState("0");
        payOrder.setTradeNo(PaymentUtil.genUniquePayOrderNo());
        payOrder.setCreateTime(LocalDateTime.now());
        payOrder.setExpireTime(LocalDateTime.now().plusMinutes(30));
        String y2F = AmountUtil.changeY2F(Long.valueOf(payOrderDTO.getTotalAmount()));
        payOrder.setTotalAmount(Integer.parseInt(y2F));
       // payOrder.setTotalAmount(payOrderDTO.getTotalAmount());
        payOrder.setCurrency("CNY");
        payOrderMapper.insert(payOrder);
        PayOrderDTO dtO = PayOrderConvert.INSTANCE.entity2dto(payOrder);
        return dtO;
    }
    //调用支付宝下单接口
    private PaymentResponseDTO<String> alipayH5(PayOrderDTO payOrderDTO) {
        //公共参数
        PayChannelParamDTO payChannelParamDTO = payChannelService.queryPayChannelParamByappIdandPlatformChannel(
                payOrderDTO.getAppId(),
                payOrderDTO.getChannel(), payOrderDTO.getPayChannel());
        if (payChannelParamDTO==null){
            throw new BusinessException(CommonErrorCode.E_300007);
        }
        String param = payChannelParamDTO.getParam();
        AliConfigParam aliConfigParam = JSONObject.parseObject(param, AliConfigParam.class);

        //业务参数
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setProductCode("QUICK_WAP_WAY");
        alipayBean.setOutTradeNo(payOrderDTO.getTradeNo());
        alipayBean.setSubject(payOrderDTO.getSubject());
        alipayBean.setBody(payOrderDTO.getBody());
        String F2y = null;
        try {
            F2y = AmountUtil.changeF2Y(Long.valueOf(payOrderDTO.getTotalAmount()));
        } catch (Exception exception) {
            throw new BusinessException(CommonErrorCode.E_300006);
        }
        alipayBean.setTotalAmount(F2y);
        alipayBean.setStoreId(payOrderDTO.getStoreId());
        alipayBean.setExpireTime("30m");
        //掉代理对接支付宝
        return agentService.createPayOrderByAliWAP(aliConfigParam,alipayBean);

    }
    public PayOrderDTO queryPayOrder(String tradeNo){
        PayOrder payOrder = payOrderMapper.selectOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getTradeNo, tradeNo));
        return PayOrderConvert.INSTANCE.entity2dto(payOrder);
    }



    private void verifyAppAndStore(Long merchantId,String appId,Long storeId){
        //判断应用手否属于当前商户
        Boolean contains = appService.queryAppInMerchant(appId, merchantId);
        if (!contains){
            throw new BusinessException(CommonErrorCode.E_200005);

        }
        //判断商店是否属于当前商户,
        Boolean contain = merchantService.queryStoreInMerchant(storeId, merchantId);
        if (!contain){
            throw new BusinessException(CommonErrorCode.E_200006);
        }
    }


}
